import xmlrpclib
import re

from zope.interface import Interface, implements
from zope.component import adapts

from borg.localrole.interfaces import ILocalRoleProvider
from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin
from AccessControl.SecurityInfo import ClassSecurityInfo
from Products.PluggableAuthService.utils import classImplements
from Globals import InitializeClass
from Products.PluggableAuthService.interfaces.plugins import IAuthenticationPlugin, IUserEnumerationPlugin, IPropertiesPlugin
from Products.PluggableAuthService.interfaces.plugins import IGroupsPlugin,IGroupEnumerationPlugin
from Products.PageTemplates.PageTemplateFile import PageTemplateFile

manage_addExamplePluginForm = PageTemplateFile('../www/addAidentuPAS',
    globals(), __name__='manage_addAidentuPluginForm')

def addAidentuPlugin(self, id, title='', xmlrpc_server='', passcode='', REQUEST=None):
    ''' Add an Aidentu PAS Plugin to Plone PAS
    '''
    o = AidentuPlugin(id, title, xmlrpc_server, passcode)
    self._setObject(o.getId(), o)

    if REQUEST is not None:
        REQUEST['RESPONSE'].redirect('%s/manage_main'
            '?manage_tabs_message=Aidentu+PAS+Plugin+added.' %
            self.absolute_url())

class AidentuPlugin(BasePlugin):
    ''' Plugin for Aidentu PAS
    '''
    meta_type = 'AIdentU PAS'
    security = ClassSecurityInfo()

    def __init__(self, id, title=None, xmlrpc_server='http://localhost:8000/cohab/xmlrpc/', passcode=''):
        self._setId(id)
        self.title = title
        self.xmlrpc_server = xmlrpc_server
        self.passcode = passcode

    # IAuthenticationPlugin implementation
    def authenticateCredentials(self, credentials):
        ''' Authenticate credentials against Aidentu database
        through XMLRPC
        ''' 
        if 'login' not in credentials or 'password' not in credentials:
            return None

        login = credentials['login']
        password = credentials['password']
        
        server = xmlrpclib.Server(self.xmlrpc_server)
        auth_user = server.entrar_aidentu(self.passcode,login,password)
        if auth_user['sucesso']:
            self._getPAS().updateCredentials(self.REQUEST,
                self.REQUEST.RESPONSE, login, password)
            return (login, login)

        return None
        
    # IPropertiesPlugin
    def getPropertiesForUser(self, user, request = None):
        server = xmlrpclib.Server(self.xmlrpc_server)
        auth_user = server.get_lista_usuarios(self.passcode,user.getId(),True)
        if auth_user:
            del auth_user[0]['id']
            return auth_user[0]
        return None

    #IUserEnumeratioPlugin
    def enumerateUsers(self, id=None, login=None, exact_match=False,
        sort_by=None, max_results=None, **kw):
        ''' Return a list of valid users identified by this plugin.
        '''
        key = id or login
        if not key:
            return None
        server = xmlrpclib.Server(self.xmlrpc_server,allow_none=True)
        lista = server.get_lista_usuarios(self.passcode,key,
                                      exact_match,sort_by,max_results)
        for i in lista:
            i['pluginid']=self.getId()
        return lista
    
    #IGroupsPlugin
    def getGroupsForPrincipal(self, principal, request=None):
        server = xmlrpclib.Server(self.xmlrpc_server,allow_none=True)
        grupos = server.get_grupos(self.passcode,principal.getUserName())
        return grupos
    
    #IGroupEnumerationPlugin
    def enumerateGroups( id=None
                       , exact_match=False
                       , sort_by=None
                       , max_results=None
                       , **kw
                       ):
        server = xmlrpclib.Server(self.xmlrpc_server,allow_none=True)
        grupos_id_list = server.get_lista_grupos(self.passcode,id,
                                           exact_match,sort_by,max_results)
        grupos_list = []
        for g in groups_id_list:
            grupos_list.append({'id':g, 'pluginid':'aidentupas'})
        
        return grupos_list
        

classImplements(AidentuPlugin, IAuthenticationPlugin, IUserEnumerationPlugin, 
                IPropertiesPlugin, IGroupsPlugin,IGroupEnumerationPlugin)
InitializeClass(AidentuPlugin)